package controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import model.BlogDao;
import model.Blog;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    //获取到数据库中的博客列表
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先尝试获取req中的blogId
        resp.setContentType("application/json;charset=utf8");
        String param = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        //如果blogId为空，就是博客列表页
        if (param == null) {
            List<Blog> blogs = blogDao.selectAll();
            //把blog对象转换成JSON格式
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.getWriter().write(respJson);
        } else {//如果不为空，就是博客详情页
            int blogId = Integer.parseInt(param);
            Blog blog = blogDao.selectOne(blogId);
            String respJson = objectMapper.writeValueAsString(blog);
            resp.getWriter().write(respJson);
        }
    }
//将博客信息保存到数据库中
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前用户信息
        HttpSession httpSession=req.getSession(false);
      if(httpSession==null){
          resp.setContentType("text/html;charset=utf8");
          resp.getWriter().write("当前用户未登录");
          return;
      }
      User user=(User)httpSession.getAttribute("user");
      if(user==null){
          resp.setContentType("text/html,charset=utf8");
          resp.getWriter().write("当前对象不存在");
          return;
      }
        //先从请求中，拿出博客标题和正文
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        resp.getWriter().write("title:"+title+" ");
        resp.getWriter().write("/n");
        resp.getWriter().write("content:"+content);

        if(title==null||"".equals(title)||content==null||"".equals(content)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("博客标题或者正文参数缺失");
            return;
        }
        Blog blog=new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setAuthorId(user.getUserId());
        BlogDao blogDao=new BlogDao();
        blogDao.insert(blog);
        resp.sendRedirect("blog_list.html");
    }
}
